<script>
export default {
  name: 'Attr'
}
</script>
<script setup>
import { useProductStore } from '@/store/modules/product'
import { storeToRefs } from 'pinia'
import $api from '@/api/index'
import { ref, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'

const productStore = useProductStore()
const { categoryIdData } = storeToRefs(productStore)

watch(
  () => productStore.categoryIdData.id3,
  newV => {
    attrInfoList.value = []
    if (!!newV) reqAttrInfoList()
  }
)

// 所选三级分类id获取到的attr信息列表和请求函数
const attrInfoList = ref([])
// 请求分类信息列表
const reqAttrInfoList = async function () {
  const { id1: c1Id, id2: c2Id, id3: c3Id } = categoryIdData.value
  const result = await $api.product.attr.reqAttrInfoList(c1Id, c2Id, c3Id)
  if (result?.data?.code === 200) {
    attrInfoList.value = result.data.data
    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 表单展示状态
const attrInfoEditor = ref(false)

// 所有选择的分类id收集
const attrInfoEditorData = ref({
  attrName: '',
  categoryId: 0,
  categoryLevel: 3,
  attrValueList: []
})

// 保存当前属值对应index的input标签的DOM
const inputDomArr = ref([])

// 打开attr编辑
const openAttrInfoEditor = function (row) {
  attrInfoEditor.value = true
  inputDomArr.value = []
  if (row) {
    attrInfoEditorData.value = JSON.parse(JSON.stringify(row))
  }
}

// 关闭attr编辑
const closeAttrInfoEditor = function () {
  attrInfoEditor.value = false
  attrInfoEditorData.value = {
    attrName: '',
    categoryId: 0,
    categoryLevel: 3,
    attrValueList: []
  }
}

// 添加attr属性值方法
const addAttrValueList = function () {
  attrInfoEditorData.value.attrValueList.push({
    valueName: '',
    editor: true
  })

  nextTick(() => {
    inputDomArr.value[inputDomArr.value.length - 1].focus()
  })
}

// 添加attr属性值方法
const removeAttrValueList = function (index) {
  attrInfoEditorData.value.attrValueList.splice(index, 1)
}
// 打开编辑属性值
const openChangeAttrValue = function (row, index) {
  row.editor = true
  nextTick(() => {
    inputDomArr.value[index]?.focus()
  })
}
// 关闭编辑属性值
const closeChangeAttrValue = function (row, index) {
  // 相同警告
  const isSome = attrInfoEditorData.value.attrValueList.some(
    (item, someIndex) => item.valueName === row.valueName && someIndex !== index
  )
  if (isSome) {
    ElMessage.error('不能有相同的值')
    nextTick(() => {
      inputDomArr.value[index].focus()
    })
    return
  }

  // 为空删除
  if (!row.valueName) removeAttrValueList(index)

  // 关闭编辑状态
  row.editor = false
}

// 保存编辑属性值
const saveChangeAttrValue = async function () {
  attrInfoEditorData.value.categoryId = categoryIdData.value.id3
  const result = await $api.product.attr.reqSaveAttrInfo(attrInfoEditorData.value)
  if (result?.data?.code === 200) {
    await reqAttrInfoList()
    ElMessage.success(attrInfoEditorData.value.id ? '更新属性成功' : '新增属性成功')
    // 重置变量值和退出编辑状态
    closeAttrInfoEditor()
    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 删除属性
const deleteAttrInfo = async function (id) {
  // 删除
  const result = await $api.product.attr.reqDeleteAttrInfo(id)
  if (result?.data?.code === 200) {
    ElMessage.success('删除属性成功')
    // 重新获取属性列表数据
    await reqAttrInfoList()
    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}
</script>

<template>
  <div>
    <!-- 三级分类选择框 -->
    <Category :isDisabled="attrInfoEditor" />
    <!-- attr展示增删改查table部分 -->
    <el-card
      style="margin-top: 15px"
      v-if="!attrInfoEditor"
    >
      <el-button
        type="primary"
        icon="Plus"
        :disabled="!categoryIdData.id3"
        @click="openAttrInfoEditor()"
        v-has="'btn.Attr.add'"
      >
        添加平台属性
      </el-button>

      <el-table
        :data="attrInfoList"
        border
        stripe
        style="margin-top: 15px"
      >
        <el-table-column
          type="index"
          width="80"
          align="center"
          label="序号"
        />
        <el-table-column
          prop="attrName"
          label="属性名字"
        />
        <el-table-column label="属性值名字">
          <template #="{ row }">
            <el-tag
              type="success"
              v-for="item of row.attrValueList"
              :key="item.id"
              class="tag_class"
            >
              {{ item?.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              @click="openAttrInfoEditor(row)"
              v-has="'btn.Attr.update'"
            />
            <el-popconfirm
              :title="`确定要删除 ${row.attrName} 吗？`"
              width="250px"
              @confirm="deleteAttrInfo(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  icon="Delete"
                  v-has="'btn.Attr.remove'"
                />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- attr编辑部分 -->
    <el-card
      style="margin-top: 15px"
      v-else-if="attrInfoEditor"
    >
      <el-form>
        <!-- 属性名字输入框 -->
        <el-form-item label="属性名字">
          <el-input
            v-model="attrInfoEditorData.attrName"
            style="width: 200px"
          />
        </el-form-item>
        <!-- 属性名字输入框 -->
        <el-form-item>
          <el-button
            type="primary"
            icon="Plus"
            :disabled="!attrInfoEditorData?.attrName"
            @click="addAttrValueList()"
            >添加属性值</el-button
          >
          <el-button>取消</el-button>
        </el-form-item>
        <!-- 属性值table -->
        <el-form-item>
          <el-table
            :data="attrInfoEditorData.attrValueList"
            border
            stripe
          >
            <el-table-column
              type="index"
              width="80"
              label="序号"
              align="center"
            />
            <el-table-column label="属性值">
              <template #="{ row, $index }">
                <span
                  v-if="!row?.editor"
                  @click="openChangeAttrValue(row, $index)"
                  >{{ row.valueName }}</span
                >
                <input
                  type="text"
                  v-model="row.valueName"
                  v-if="row?.editor"
                  :ref="el => (inputDomArr[$index] = el)"
                  @blur="closeChangeAttrValue(row, $index)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{ row, $index }">
                <el-popconfirm
                  :title="`你确定要删除 ${row.valueName}`"
                  width="250px"
                  @confirm="removeAttrValueList($index)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      icon="Delete"
                    />
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 编辑操作按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            @click="saveChangeAttrValue()"
            :disabled="attrInfoEditorData.attrValueList.length === 0"
          >
            保存
          </el-button>
          <el-button @click="closeAttrInfoEditor()"> 取消 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
// start

.tag_class {
  margin-right: 15px;
}
</style>
